/**
 * Task scheduling functionality using node-cron
 * Manages cron-based execution of web opening tasks
 */
import cron from 'node-cron';
import { openUrl } from './browser.js';
import { validateConfig } from './config.js';

/**
 * Scheduler class for managing cron jobs
 */
export class Scheduler {
  constructor(config) {
    this.config = config;
    this.task = null;
    this.running = false;
  }

  /**
   * Start the scheduled task
   */
  start() {
    if (this.running) {
      throw new Error('Scheduler is already running');
    }

    this.task = cron.schedule(this.config.cron, async () => {
      await this.executeTask();
    }, {
      scheduled: false
    });

    this.task.start();
    this.running = true;
    console.log(`Scheduler started: ${this.config.url} at ${this.config.cron}`);
  }

  /**
   * Stop the scheduled task
   */
  stop() {
    if (!this.running) return;

    if (this.task) {
      this.task.stop();
      this.task = null;
    }
    
    this.running = false;
    console.log('Scheduler stopped');
  }

  /**
   * Check if scheduler is running
   * @returns {boolean} Running state
   */
  isRunning() {
    return this.running;
  }

  /**
   * Execute the task once
   * @param {Object} options - Execution options
   * @returns {Promise<Object>} Execution result
   */
  async executeTask(options = {}) {
    try {
      console.log(`Opening: ${this.config.url}`);
      const result = await openUrl(this.config.url, options);
      
      // Handle multiple windows with delay
      if (this.config.multiple && this.config.delay > 0) {
        setTimeout(async () => {
          await openUrl(this.config.url, options);
        }, this.config.delay);
      }
      
      return result;
    } catch (error) {
      console.error('Task execution failed:', error.message);
      throw error;
    }
  }
}

/**
 * Create and configure a scheduler instance
 * @param {Object} config - Configuration object
 * @returns {Scheduler} Configured scheduler
 */
export function createScheduler(config) {
  const validation = validateConfig(config);
  if (!validation.isValid) {
    throw new Error(`Configuration validation failed: ${validation.errors.join(', ')}`);
  }

  if (!cron.validate(config.cron)) {
    throw new Error(`Invalid cron expression: ${config.cron}`);
  }

  return new Scheduler(config);
}